<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <title>VCEX Checkout</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
      .glass-bg {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(15px) saturate(150%);
        -webkit-backdrop-filter: blur(15px) saturate(150%);
        border-top: 1px solid rgba(255, 255, 255, 0.4);
      }
      .digit-box {
        background: linear-gradient(to bottom, #fff 0%, #ddd 50%, #fff 100%);
        color: #111; padding: 3px 6px; border-radius: 4px; font-weight: bold;
        min-width: 28px; text-align: center; font-size: 1.25rem; line-height: 1.5rem;
        box-shadow: inset 0 -2px 4px rgba(0,0,0,.3), inset 0 2px 4px rgba(255,255,255,.6);
        position: relative;
      }
      .digit-box::after {
        content: ""; position: absolute; top: 50%; left: 0; right: 0; height: 1px; background: rgba(0,0,0,.3);
      }
      .btn-disabled { opacity: .6; cursor: not-allowed; filter: grayscale(30%) }

      /* 验证样式（柔和） */
      input.error, select.error { border-color: #f87171!important; background:#fff8f8!important; transition: .2s }
      .field-wrapper { position: relative; }
      .error-text {
        position: absolute; right: 8px; top: 50%; transform: translateY(-50%);
        font-size: .7rem; color: #dc2626; background: #fff; padding: 0 4px; border-radius: 3px; pointer-events: none; white-space: nowrap;
      }
      @media (max-width: 640px){ .error-text{ font-size:.65rem; right:6px } }
    </style>

    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-32RHR5GY2W"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){ dataLayer.push(arguments); }
      gtag('js', new Date());
      gtag('config', 'G-32RHR5GY2W');
    </script>
  </head>

  <body class="bg-gray-100 min-h-screen">
    <main class="max-w-7xl mx-auto p-2 md:p-6 lg:p-8 space-y-4">
      <!-- ✅ Order summary -->
      <div class="sticky top-0 z-50 bg-white border-b shadow-md p-3 flex gap-3">
        <div class="flex flex-col items-center gap-1 flex-shrink-0 w-24">
          <img id="orderThumb" src="" alt="product" class="w-20 mb-1 object-contain rounded border">
          <button id="editSelection" class="px-2 py-0.5 bg-gray-200 hover:bg-gray-300 text-gray-600 text-[11px] rounded flex items-center gap-1">✏️ Edit</button>
        </div>
        <div class="flex-1 min-w-0 flex flex-col justify-start">
          <h2 class="text-sm font-bold text-gray-800 truncate">Your Selection</h2>
          <p id="orderSummary" class="text-red-600 font-semibold text-sm">Loading...</p>
          <p id="buyTip" class="text-xs text-green-600 font-medium"></p>
          <p class="text-xs text-gray-600"><span id="unitPrice" class="font-semibold">$0.00</span></p>
        </div>
        <div class="flex flex-col justify-end items-end text-right">
          <span class="text-xs text-gray-500">Total:</span>
          <span id="subtotal" class="text-base md:text-lg font-bold text-red-600">$0.00</span>
        </div>
      </div>

      <!-- ✅ Payment info -->
      <aside class="bg-white border-2 border-red-600 rounded-lg p-2 sm:p-6 space-y-2">
        <div class="bg-gradient-to-r from-red-700 to-red-500 text-white text-center rounded-lg p-2 shadow-md">
          <div class="flex items-center justify-center gap-2 text-xl font-extrabold">
            <span>💳</span><span>PAYMENT INFORMATION</span>
          </div>
          <div class="text-xs font-semibold opacity-90 mt-1">FINAL STEP!</div>
        </div>

        <div class="flex justify-center items-center gap-2 bg-red-800 text-white px-4 py-2 rounded-lg shadow-md">
          <span class="text-2xl">⏱️</span>
          <div id="countdown" class="flex gap-1 text-3xl font-mono items-center"></div>
        </div>

        <div class="bg-green-50 border border-green-300 rounded-lg p-2 flex justify-center shadow-sm">
          <div class="text-center">
            <p class="flex items-center justify-center gap-2 text-green-700 font-bold">
              <span class="text-[20px]">🚚</span><span>FREE Shipping</span>
            </p>
            <p class="text-green-600 text-sm">Ships in 3–7 business days</p>
          </div>
        </div>

        <!-- ✅ 表单（新增 Address2，可选；顺序/文案优化） -->
        <form id="checkoutForm" class="grid grid-cols-1 gap-3">
          <div class="grid grid-cols-2 gap-3">
            <div class="field-wrapper"><input id="firstName" class="border rounded p-2 w-full" placeholder="First Name" required></div>
            <div class="field-wrapper"><input id="lastName" class="border rounded p-2 w-full" placeholder="Last Name" required></div>
          </div>

          <div class="field-wrapper"><input id="address"  class="border rounded p-2 w-full" placeholder="Street Address" required></div>
          <div class="field-wrapper"><input id="address2" class="border rounded p-2 w-full" placeholder="Apartment, suite, etc. (optional)"></div>

          <div class="grid grid-cols-2 gap-3">
            <div class="field-wrapper"><input id="city"  class="border rounded p-2 w-full" placeholder="City" required></div>
            <div class="field-wrapper"><input id="state" class="border rounded p-2 w-full" placeholder="State/County/Province" required></div>
          </div>

          <div class="grid grid-cols-2 gap-3">
            <div class="field-wrapper"><input id="postalCode" class="border rounded p-2 w-full" placeholder="ZIP/Postal Code" required></div>
            <div class="field-wrapper">
              <!-- 若你坚持默认美国，可把第一项改回 <option>United States</option> 并去掉占位项 -->
              <select id="country" class="border rounded p-2 w-full">
                <option value="">Select Country</option>
                <option>United States</option>
                <option>Canada</option>
                <option>United Kingdom</option>
              </select>
            </div>
          </div>

          <div class="field-wrapper"><input id="phone" class="border rounded p-2 w-full" placeholder="Phone Number" required></div>
          <div class="field-wrapper"><input id="email" type="email" class="border rounded p-2 w-full" placeholder="Email Address" required></div>
        </form>
      </aside>
    </main>

    <!-- ✅ Trust badges（信用标识：Stripe/Visa/Mastercard/SSL/Guarantee） -->
    <div class="max-w-7xl mx-auto mt-6 px-4 text-center space-y-3 mb-4">
      <p class="text-sm text-gray-600 font-medium">
        Secure Payment Powered by <span class="font-bold">Stripe</span>
      </p>
      <div class="flex justify-center items-center gap-6 flex-wrap">
        <img src="https://vcexbuck.us-lax-1.linodeobjects.com/statics/aqzf0-spe.jpg" class="h-8 object-contain" alt="stripe" />
        <img src="https://vcexbuck.us-lax-1.linodeobjects.com/statics/aqzf0-vsa.jpg" class="h-8 object-contain" alt="visa" />
        <img src="https://vcexbuck.us-lax-1.linodeobjects.com/statics/Mastercard-logo.svg" class="h-8 object-contain" alt="mastercard" />
        <img src="https://vcexbuck.us-lax-1.linodeobjects.com/statics/ssllogo.png" class="h-8 object-contain" alt="ssl" />
        <img src="https://vcexbuck.us-lax-1.linodeobjects.com/statics/guarantee-badge.png" class="h-8 object-contain" alt="guarantee" />
      </div>
      <p class="text-xs text-gray-500">🔒 256-bit SSL Encryption · PCI DSS Compliant · 100% Secure Checkout</p>
    </div>

    <!-- 🏢 Company Footer（与原版一致） -->
    <footer class="mt-8 text-center text-xs text-gray-500 border-t pt-4 mb-48">
      <p>© 2025 LeadMob All rights reserved.</p>
      <p class="mt-1">Your trusted partner in health & wellness.</p>
    </footer>

    <!-- ✅ Checkout bar -->
    <div class="fixed bottom-0 left-0 w-full glass-bg border-t shadow-lg z-50 pb-8" style="box-shadow: 0 2px 12px rgba(0,0,0,.2);">
      <div class="max-w-7xl mx-auto flex flex-col md:flex-row items-center justify-between px-4 py-2 gap-2">
        <p class="text-lg font-bold text-gray-800">Total: <span id="grandTotal" class="text-red-600">$0.00</span></p>
        <button id="checkoutBtn" class="bg-green-500 hover:bg-green-600 active:bg-green-700 text-white font-bold py-2 px-6 rounded-lg shadow-md">✅ Checkout Securely</button>
      </div>
      <div class="text-center text-xs text-gray-600 pb-3">🛡️ 100% Satisfaction Guarantee</div>
    </div>

    <script>
      // countdown（原样）
      let countdownTime = 10 * 60, countdownEl = document.getElementById("countdown");
      function renderTime(){
        let m = String(Math.floor(countdownTime/60)).padStart(2,"0");
        let s = String(countdownTime%60).padStart(2,"0");
        let str = `00:${m}:${s}`; countdownEl.innerHTML = "";
        str.split("").forEach(c => { countdownEl.innerHTML += (c === ":") ? `<span class="text-2xl font-bold">:</span>` : `<span class="digit-box">${c}</span>`; });
      }
      setInterval(()=>{ if(countdownTime>0){ countdownTime--; renderTime(); } },1000); renderTime();

      function getCurrencySymbol(code){
        const map={usd:"$",eur:"€",gbp:"£",hkd:"HK$",cny:"¥",jpy:"¥",aud:"A$",cad:"C$"};
        return map[String(code||"").toLowerCase()]||"$";
      }

      const params = new URLSearchParams(window.location.search);
      const sub1 = params.get('sub1'), sub2 = params.get('sub2'), sub3 = params.get('sub3'), sub4 = params.get('sub4');
      const productId = params.get('id');
      const orderThumbEl = document.getElementById('orderThumb'),
            orderSummaryEl = document.getElementById('orderSummary'),
            unitPriceEl   = document.getElementById('unitPrice'),
            subtotalEl    = document.getElementById('subtotal'),
            grandTotalEl  = document.getElementById('grandTotal'),
            checkoutBtn   = document.getElementById('checkoutBtn');

      let packageTotal=0, currencySign='$';
      function updateTotals(){ subtotalEl.textContent = `${currencySign}${packageTotal.toFixed(2)}`; grandTotalEl.textContent = `${currencySign}${packageTotal.toFixed(2)}`; }

      document.getElementById('editSelection').onclick = () => window.history.back();

      // 输入即时清错
      document.getElementById('checkoutForm').addEventListener('input', (e)=>{
        const el=e.target, wrap=el.closest('.field-wrapper'); if(!wrap) return;
        const hint=wrap.querySelector('.error-text');
        if(el.value.trim()!=='' && !(el.id==='country' && el.value==='')){ el.classList.remove('error'); if(hint) hint.remove(); }
      });
      const countryEl = document.getElementById('country');
      countryEl.addEventListener('change', ()=>{ const wrap=countryEl.closest('.field-wrapper'), hint=wrap.querySelector('.error-text'); if(countryEl.value!==''){ countryEl.classList.remove('error'); if(hint) hint.remove(); } });

      // 校验
      // ✅ 去掉 email，让它变成可选填
      const requiredFields = [
        "firstName",
        "lastName",
        "postalCode",
        "city",
        "address",
        "country",
        "state",
        "phone",
		"email"
      ];
      const fieldMessages={firstName:"First name",lastName:"Last name",address:"Street address",city:"City",state:"State",postalCode:"ZIP / Postal Code",country:"Select country",phone:"Phone number",email:"Email"};
      function validateForm(){
        let invalid=false;
        requiredFields.forEach(id=>{
          const el=document.getElementById(id), wrap=el.closest('.field-wrapper'); let hint=wrap.querySelector('.error-text');
          const isEmpty=!el.value.trim() || (id==='country' && el.value==='');
          if(isEmpty){ invalid=true; el.classList.add('error'); if(!hint){ hint=document.createElement('div'); hint.className='error-text'; hint.textContent=fieldMessages[id]||'Required'; wrap.appendChild(hint); } }
          else{ el.classList.remove('error'); if(hint) hint.remove(); }
        });
        if(invalid){ document.querySelector('.error')?.scrollIntoView({behavior:'smooth',block:'center'}); return false; }
        return true;
      }

      // 合并 Address1 + Address2
      function buildLine1(){
        const a1 = document.getElementById('address').value.trim();
        const a2 = document.getElementById('address2').value.trim();
        return a2 ? `${a1}, ${a2}` : a1;
      }

      // Checkout（原有逻辑 + vcex2 + sub1~4 全保留）
      checkoutBtn.onclick = async () => {
        if(!validateForm()) return;
        try{
          gtag('event','checkout_click',{ button_id:'checkoutBtn', button_text:'Checkout Securely', product_id: productId, page_path: location.pathname });

          checkoutBtn.disabled=true; checkoutBtn.classList.add('btn-disabled'); checkoutBtn.textContent='Processing...';

          const data = {
            product_list: [{ product_id: Number(productId), quantity: 1 }],
            first_name: document.getElementById('firstName').value,
            last_name:  document.getElementById('lastName').value,
            phone:      document.getElementById('phone').value,
            country:    document.getElementById('country').value,
            state:      document.getElementById('state').value,
            city:       document.getElementById('city').value,
            postal_code:document.getElementById('postalCode').value,
            line1:      buildLine1(),
            line2:      '',
            email:      document.getElementById('email').value,
            v:          'vcex2'
          };
          if(sub1) data.sub1=sub1; if(sub2) data.sub2=sub2; if(sub3) data.sub3=sub3; if(sub4) data.sub4=sub4;

          const res  = await fetch('https://vitacorex.com/vcex/order/create_checkout_session',{ method:'POST', headers:{'Content-Type':'application/json','Accept':'application/json'}, body: JSON.stringify(data) });
          const json = await res.json();
          if(json.code && json.code.checkout_url){ window.location.href = json.code.checkout_url; }
          else{ throw new Error(json.msg || 'Checkout failed'); }
        }catch(e){
          console.error(e); alert('Error creating checkout session');
          checkoutBtn.disabled=false; checkoutBtn.classList.remove('btn-disabled'); checkoutBtn.textContent='✅ Checkout Securely';
        }
      };

      // 加载商品（原样）
      async function loadProduct(){
        if(!productId){ document.getElementById('orderSummary').textContent='No product selected'; return; }
        try{
          const res = await fetch(`https://vitacorex.com/vcex/order/get_product_byID?product_id=${encodeURIComponent(productId)}`);
          const json = await res.json(); if(!json || !json.data) throw new Error('No data');
          const p=json.data;
          currencySign = getCurrencySymbol(p.currency);
          packageTotal = parseFloat(p.total_price || '0') || 0;
          orderThumbEl.src = p.image_url || '';
          document.getElementById('orderSummary').textContent = `${p.name||''} ${p.sub_title||''}`.trim();
          const perBottle = parseFloat(p.price || '0') || 0;
          unitPriceEl.textContent = `${currencySign}${perBottle.toFixed(2)}${p.unit_text||''}`;
          document.getElementById('buyTip').textContent = p.buy_tip || '';
          updateTotals();
        }catch(e){
          console.error(e); document.getElementById('orderSummary').textContent='Failed to load product';
        }
      }
      loadProduct();
    </script>
  </body>
</html>
